package plenprojects.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import plenprojects.model.UserDetails;

public class ChatServiceDao {
	
	private JdbcTemplate template;

	public ChatServiceDao(JdbcTemplate template) {
		
		this.template = template;
	}
	
	public UserDetails getDetailsFromUsername(String username) {
		
		List<UserDetails> user = template.query("SELECT * FROM users "
				 + "WHERE username = ?", new RowMapper<UserDetails>() {

					 public UserDetails mapRow(ResultSet rs, int i) throws SQLException {

						 UserDetails ud = new UserDetails();

						 ud.setUsername(rs.getString("username"));
						 ud.setHash(rs.getString("pwd_hash"));
						 ud.setDescription(rs.getString("description"));
						 ud.setHasImage(rs.getBoolean("has_image"));

						 return ud;
					 }

				 }, username);
		
		if(user.size() == 1) {
			
			return user.get(0);
		}
		else {
			
			return null;
		}
	}
	
	public boolean addUser(UserDetails details) {
		
		template.update("INSERT INTO users (username, pwd_hash, description, has_image)"
					  + "VALUES (?, ?, ?, ?)", details.getUsername(), details.getHash(), details.getDescription(), details.hasImage());
		
		return true;
	}
	
	public boolean exists(String username) {
		
		return template.queryForInt("SELECT EXISTS(SELECT * FROM users WHERE username = ?)", username) > 0;
	}
}
